import path from "node:path";
import fs from "node:fs";

export const createFunction = (rootPath: string) => {
  return (path: string = "") => {
    return rootPath + path;
  };
};

export const createWithTextFunction = (rootPath: string) => {
  return (filePath: string = "") => {
    const relativePath = "./" + rootPath + filePath;
    let absolutePath = path.resolve(relativePath);
    let text = "";
    if (filePath === "") {
      absolutePath += "/index.md";
    } else {
      absolutePath += ".md";
    }
    if (fs.existsSync(absolutePath)) {
      const content = fs.readFileSync(absolutePath, { encoding: "utf-8" });
      if (content.length > 0) {
        const result = content.match(/#\ (.*?)\r\n/);
        if (result !== null) {
          text = result[1];
        }
      }
    }
    return {
      text: text,
      link: rootPath + filePath,
    };
  };
};

export function useFunction(filePath: string): [
  (path?: string) => string,
  (filePath?: string) => {
    text: string;
    link: string;
  }
] {
  const func = createFunction(filePath);
  const funcWithText = createWithTextFunction(filePath);
  return [func, funcWithText];
}
